import { defineStore } from "pinia";
import { ref } from "vue";
import { useRouter } from "vue-router";

export const useUserStore = defineStore("user", () => {
  const user = ref(null);
  const token = ref(localStorage.getItem("token") || null);
  const router = useRouter();

  const login = async (credentials) => {
    // 这里替换为实际的API调用
    try {
      // 模拟API请求
      await new Promise((resolve) => setTimeout(resolve, 1000));

      if (
        credentials.username === "admin" &&
        credentials.password === "123456"
      ) {
        const mockToken = "mock-jwt-token";
        user.value = { username: credentials.username };
        token.value = mockToken;
        localStorage.setItem("token", mockToken);
        return true;
      } else {
        throw new Error("用户名或密码错误");
      }
    } catch (error) {
      throw error;
    }
  };

  const logout = () => {
    user.value = null;
    token.value = null;
    localStorage.removeItem("token");
    router.push("/login");
  };

  return { user, token, login, logout };
});
